#!/bin/bash

# 项目根目录
ROOT_DIR="$(pwd)"

# 要替换的包名
OLD_PACKAGE="com.aishop"
NEW_PACKAGE="com.wgh"

# 将包名转换为目录路径
OLD_PATH="$(echo $OLD_PACKAGE | tr '.' '/')"
NEW_PATH="$(echo $NEW_PACKAGE | tr '.' '/')"

# 后端项目列表
BACKEND_PROJECTS=("shop-product" "shop-order" "shop-cart" "shop-pay" "shop-inventory" "shop-search" "shop-common" "shop-gateway")

# 重命名Java源文件中的包名
rename_package_in_files() {
    echo "正在替换源文件中的包名: $OLD_PACKAGE -> $NEW_PACKAGE"
    for project in "${BACKEND_PROJECTS[@]}"; do
        if [ -d "$ROOT_DIR/$project/src/main/java" ]; then
            find "$ROOT_DIR/$project/src/main/java" -type f -name "*.java" -exec sed -i '' "s/$OLD_PACKAGE/$NEW_PACKAGE/g" {} \;
            echo "  已处理项目: $project"
        fi
    done
}

# 重命名Maven配置文件中的groupId
rename_groupId_in_poms() {
    echo "正在替换pom.xml中的groupId: $OLD_PACKAGE -> $NEW_PACKAGE"
    find "$ROOT_DIR" -name "pom.xml" -exec sed -i '' "s/<groupId>$OLD_PACKAGE<\/groupId>/<groupId>$NEW_PACKAGE<\/groupId>/g" {} \;
    find "$ROOT_DIR" -name "pom.xml" -exec sed -i '' "s/groupId>$OLD_PACKAGE/groupId>$NEW_PACKAGE/g" {} \;
    echo "  已处理所有pom.xml文件"
}

# 重命名包目录结构
rename_package_directories() {
    echo "正在重命名包目录结构: $OLD_PATH -> $NEW_PATH"
    for project in "${BACKEND_PROJECTS[@]}"; do
        if [ -d "$ROOT_DIR/$project/src/main/java/$OLD_PATH" ]; then
            # 创建新的包路径
            NEW_DIR="$ROOT_DIR/$project/src/main/java/$NEW_PATH"
            mkdir -p "$(dirname $NEW_DIR)"
            
            # 移动文件到新路径
            mv "$ROOT_DIR/$project/src/main/java/$OLD_PATH" "$NEW_DIR"
            
            # 清理旧的空目录
            find "$ROOT_DIR/$project/src/main/java" -type d -empty -delete
            
            echo "  已重命名项目 $project 的包目录"
        fi
    done
}

# 执行重命名操作
main() {
    echo "开始执行包名重命名任务..."
    rename_package_in_files
    rename_groupId_in_poms
    rename_package_directories
    echo "包名重命名任务完成!"
}

# 执行主函数
main